/**
  *	This class is responsible for AJAX operations
  *
  *	@author Vytenis Urbonavicius <vytenis.urbonavicius@myhost.lt>
  *	@version 0.0
  */
function comancheAjax() {
	
	function idle() {}
	this.onAjaxNotInitialized = idle;
	this.onAjaxRequestSetUp = idle;
	this.onAjaxRequestSent = idle;
	this.onAjaxRequestInProcess = idle;
	this.onAjaxRequestComplete = idle;
	this.onAjaxTimeout = idle;
	this.request_number = 0;
	this.lastAjaxResponse = undefined;
	this.ajaxObject = undefined;
	this.stateChangedEventGenerator = function ( comancheAjaxObject, request_number ) {
		return function() {
			if ( comancheAjaxObject.ajaxObject.readyState == 4 ) {
				if ( request_number == comancheAjaxObject.request_number ) {
					comancheAjaxObject.lastAjaxResponse = comancheAjaxObject.ajaxObject.responseText;
					comancheAjaxObject.rebuildAjax();
					comancheAjaxObject.onAjaxRequestComplete();
				}
			}
		}
	};
	this.rebuildAjax = function() {
		this.request_number++;
		try {
			this.ajaxObject = new XMLHttpRequest();
		} catch( e ) {
			try {
				this.ajaxObject = new ActiveXObject( "Msxml2.XMLHTTP" );
			} catch( e ) {
				try {
					this.ajaxObject = new ActiveXObject( "Microsoft.XMLHTTP" );
				} catch( e ) {}
			}
		}
		if ( this.ajaxObject != undefined ) {
			this.ajaxObject.onreadystatechange = this.stateChangedEventGenerator( this, this.request_number );
		}
		
	};
	this.getResponse = function() {
		return this.lastAjaxResponse;
	};

	this.sendRequest = function ( address, method, arguments ) {
		
		this.rebuildAjax();
		
		if ( this.ajaxObject.readyState != 0 ) {
			return false;
		}
		
		if ( ( method != "GET" ) && ( method != "POST" ) ) {
			return false;
		}
		
		if ( method == "GET" ) {
			address += '?' + arguments;
		}
		
		this.ajaxObject.open( method, address, true );
		
		if ( method == "GET" ) {
			this.ajaxObject.send( null );
		} else {
			this.ajaxObject.setRequestHeader( "Content-type", "application/x-www-form-urlencoded" );
			this.ajaxObject.setRequestHeader( "Content-length", arguments.length );
			this.ajaxObject.setRequestHeader( "Connection", "close" );
			this.ajaxObject.send( arguments );
		}
		
		return true;
		
	};
	
}